// index.js
// 获取应用实例
const app = getApp()
import user from '../../utils/user.js'
import {
    goApp,
    goAppList
} from '../../utils/util'
import {
    getTeamList,
    upAvatar,
    getAccountExpireNotify,
    getNewTeamList,
    getAccountProductInfoSimplify,
    getDetectRecord,
    setAttention
} from '../../api/app.js'
import global from '../../utils/global'
import dayjs from 'dayjs'
Page({
    data: {
        showAttention: false,
        isPopupOpenPay: false,
        isOpenPay: false,
        isOpenAlipayAccount: false,
        showopenvipopoup: false,
        shownotGetpoup: true,
        top: app.globalData.menuTop,
        menu: [],
        menu2: [{
            icon: '/assets/img/space/flow.png',
            text: '审批流设置',
            path: 'applet::/pages/flow/index/index'
        }],
        menu3: [{
            icon: '/assets/img/space/setting.png',
            text: '系统设置',
            path: 'applet::/pages/setting/setting'
        }],
        position: '',
        userName: '',
        avatar: '',
        companyName: '',
        isAdmin: false,
        isSupperAdmin: false,
        teamList: [],
        balance: 0,
        auditStatus: true, // 当前企业是否开通
        accountProductInfo: {}, // 当前余额信息集合
        expirationTime: {}, // 到期时间
        isLogon: true,
        isFatherLogon: false,
        mini: {}
    },
    onToPayInfo(e) {
        wx.navigateTo({
            url: '/packageProductInfo/page/payInfo/payInfo?i=' + e.currentTarget.dataset.i,
        })
    },
    onToInfo(e) {
        console.log(e)
        // wx.navigateTo({
        //     url: '/pages/card-clamps/card-clamps?currrent=' + e.currentTarget.dataset.i,
        // })
        wx.navigateTo({
            url: '/packageProductInfo/page/insureInfo/insureInfo?currrent=' + e.currentTarget.dataset.i,
        })
    },
    async onOpenTyx() {
        const result = await getDetectRecord({
            type: 4
        })
        console.log(result)
        if (result == undefined) {
            wx.navigateTo({
                url: '/packageMicroInsurance/pages/application-state/application-state?state=0&name=您暂未开通 微信支付商户号&tips=请联系商务开通后申请',
            })
            return
        } else if (result.status == 3) {
            wx.navigateTo({
                url: '/packageMicroInsurance/pages/application-state/application-state?state=1&name=该申请通过后会及时通知超级管理员&title=提交成功！&tips=请关注微信通知',
            })
            return
        } else if (result.status == 5) {
            wx.navigateTo({
                url: '/packageMicroInsurance/pages/application-state/application-state?state=2&name=点击返回后，请重新申请开通团意日保&title=审核失败！',
            })
            return
        } else if (result.status == 2) {
            wx.navigateTo({
                url: '/packageMicroInsurance/pages/application/application',
            })
            return
        }
    },
    topersonalmsg() {
        wx.navigateTo({
            url: '/pages/personalmsg/personalmsg',
        })
    },
    qgz() {
        this.setData({
            showAttention: false
        })
        setAttention({
            openId: user.openid,
            mpOpenid: '1',
            isAttention: 1
        })
        goAppList([{
            url: 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd5c6159f72a9705f&redirect_uri=https://front.51zidan.com/mini-auth/pay.html?' + encodeURIComponent('openid=' + user.openid) + '&response_type=code&scope=snsapi_base#wechat_redirect',
            time: 3000
        },
        {
            url: 'applet::/pages/web-view/web-view?path=' + encodeURIComponent('https://mp.weixin.qq.com/s/BRtIsq0krGPepJDFAVcVWQ'),
            type: 'redirectTo'
        }
        ])
    },
    onCloseVipPop() {
        this.setData({
            showopenvipopoup: false
        })
    },
    onClosenotGetPop() {
        this.setData({
            shownotGetpoup: false
        })
    },
    onLoad() {
        const mini = wx.getAccountInfoSync()
        const version = mini.miniProgram.version || mini.miniProgram.envVersion

        this.setData({
            menu: [

                // {
                //     icon: '/assets/img/space/examine.png',
                //     text: '审批管理',
                //     path: 'applet::/packagePay/pages/examine/index/index'
                // },
                {
                    icon: '/assets/img/space/opinion.png',
                    text: '意见与反馈',
                    path: 'applet::/packageOther/pages/opinion/opinion'
                },
                // {
                //     icon: '/assets/img/space/message.png',
                //     text: '打开消息通知',
                //     path: 'https://mp.weixin.qq.com/s/BRtIsq0krGPepJDFAVcVWQ'
                // },
                {
                    icon: '/assets/img/space/use-computer.png',
                    text: '使用电脑端',
                    path: 'applet::/packagePay/pages/major-edition/major-edition'
                },
                // {
                //     icon: '/assets/img/space/invoice.png',
                //     text: '发票下载',
                //     path: 'applet::/packagePay/pages/invoice/invoice'
                // },
                {
                    icon: '/assets/img/space/about.png',
                    text: '关于',
                    subText: version,
                    path: 'applet::/packagePay/pages/handset-info/handset-info'
                },
                {
                    istop: true,
                    icon: '/assets/img/space/change.png',
                    text: '切换企业',
                    path: 'applet::/pages/changeCompany/changeCompany'
                }
            ]
        })
        // const index = this.data.menu.findIndex(i => {
        // 	return i.path === "applet::/pages/changeCompany/changeCompany"
        // })
        // if (index !== -1) {
        // 	this.data.menu[index].subText = version
        // 	this.setData({
        // 		['menu' [index]]: this.data.menu[index]
        // 	})
        // }
        // console.log(111, version, this.data.menu);
    },
    onShow() {
        console.log(global, 'global')
        this.getTabBar().setData({
            selected: 2
        })
        user.waitLogin().then(() => {
            console.log(global, '通过登录')
            console.log(user.hasOpenid, user.isAttention, 'sugiudgiu')
            this.setData({
                isOpenPay: !!user.isOpenPaySalary,
                isOpenAlipayAccount: !!user.isOpenAlipayAccount,
                isFatherLogon: global.token ? true : false
            })
            if (user.isAdmin) {
                this.getNewTeamNum()
            }
            if (!user.hasOpenid || !user.isAttention) {
                this.setData({
                    showAttention: true
                })
            }
            // 获取团队列表
            getTeamList({
                companyId: user.companyId,
                userName: ''
            }).then(res => {
                this.setData({
                    teamList: res
                })
            })
            // 设置用户信息显示
            this.setData({
                userName: user.userName,
                avatar: user.avatarUrl,
                position: user.position,
                companyName: user.companyName,
                isAdmin: user.isAdmin,
                isSupperAdmin: user.isSuperAdmin,
                auditStatus: user.auditStatus
            })
            // 如果是管理员则显示企业余额
            // if(user.isAdmin && user.auditStatus){
            //     getCompanyBalance({
            //         companyId: user.companyId
            //     }).then(res=>{
            //         this.setData({
            //             balance: res.availableAmount
            //         })
            //     })
            // }
            this.getAccountProductInfo()
            this.getAccountExpireNotify()
        }).catch(() => {
            this.setData({
                isFatherLogon: global.token ? true : false
            })
        })
    },
    // 账户到期提示接口
    async getAccountExpireNotify() {
        const result = await getAccountExpireNotify()
        // const system = await wx.getSystemInfo()
        result.accountExpireTime = result.accountExpireTime ? dayjs(result.accountExpireTime).format('YYYY/MM/DD').replace(/\//g, '-') : null
        this.setData({
            expirationTime: result
        })
    },
    getAccountProductInfo() {
        getAccountProductInfoSimplify().then(res => {
            this.setData({
                accountProductInfo: res
            })
            console.log(this.data.accountProductInfo, 'accountProductInfo')
        })
    },
    toqygl() {
        wx.navigateTo({
            url: '/pages/enterprise/enterprise',
        })
    },
    // 前往功能页面
    goPath(event) {
        if (!user.userId) {
            app.confirm('您还未登录，是否立即登录？').then(() => {
                this.login()
            })
            return 0
        }
        if ((!user.hasOpenid || !user.isAttention) && event.currentTarget.dataset.text === '打开消息通知') {
            // setAttention({
            //     openId: user.openid,
            //     mpOpenid: '1',
            //     isAttention: 1
            // })
            goAppList([{
                url: 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd5c6159f72a9705f&redirect_uri=https://front.51zidan.com/mini-auth/pay.html?' + encodeURIComponent('openid=' + user.openid) + '&response_type=code&scope=snsapi_base#wechat_redirect',
                time: 3000
            },
            {
                url: 'applet::/pages/web-view/web-view?path=' + encodeURIComponent('https://mp.weixin.qq.com/s/BRtIsq0krGPepJDFAVcVWQ'),
                type: 'redirectTo'
            }
            ])
        }

        goApp(event.currentTarget.dataset.path)
    },
    // 查看团队列表
    goTeamList() {
        wx.navigateTo({
            // url: '/pages/team-list/team-list'
            url: '/pages/team-management/team-management'
        })
    },
    // 添加团队成员
    addTeamList() {
        wx.navigateTo({
            url: '/pages/master-invitation-qrcode/master-invitation-qrcode'
        })
    },
    // 登录
    login() {
        user.goRegister()
    },
    // 切换企业
    switchEnterprise() {
        wx.navigateTo({
            url: '/pages/changeCompany/changeCompany'
        })
    },
    onShareAppMessage() {
        return {
            title: user.userName + '邀请您加入「' + user.companyName + '」' + '项目',
            path: '/pages/index/index?scene=' + encodeURIComponent('uId=' + user.userId + '&cId=' + user.companyId),
            imageUrl: '/packagePay/assets/img/resident/share.png'
        }
    },
    // 去卡包
    goCardBag() {
        console.log('点击啦')
        wx.navigateTo({
            url: '/pages/card-clamps/card-clamps?eleSign=' + (this.data.accountProductInfo.eleSign.isOpen ? 1 : 0)
        })
    },
    // 更新头像
    onChooseAvatar(event) {
        console.log(event, 'event')
        wx.uploadFile({
            url: global.baseUrl + '/api/v1/pay/wesure-report-case/upload',
            filePath: event.detail.avatarUrl,
            name: 'file',
            formData: {
                usePath: '1'
            },
            success: (res) => {
                console.log(JSON.parse(res.data).data.fileUrl, '上传成功')
                user.avatarUrl = JSON.parse(res.data).data.fileUrl
                this.setData({
                    avatar: JSON.parse(res.data).data.fileUrl
                })
                upAvatar({
                    userHeadUrl: user.avatarUrl
                }).then(() => {
                    app.toast('头像更新成功！', 'success')
                })
            }

        })
    },
    // 忽略发薪
    expireCancel() {
        this.setData({
            'expirationTime.status': 0
        })
    },
    // 去续费
    onGoRecharge() {
        console.log('点击啦')
        // 携带 payRenew 参数 该参数是 说明 续费过来的
        wx.navigateTo({
            url: '/packageInsurance/pages/insurance-recharge-bullet/insurance-recharge-bullet?type=payRenew'
        })
    },
    onGoPopupOpenPay(e) {
        wx.navigateTo({
            url: '/pages/product-presentation/product-presentation?type=' + e.currentTarget.dataset.i,
        })
        // this.setData({
        //     isPopupPay: true
        // })
    },
    // 关闭弹窗
    onClose() {
        this.setData({
            isPopupPay: false
        })
    },
    onToVipInfo() {
        wx.navigateTo({
            url: '/pages/vipCardInfo/vipCardInfo',
            // url: '/pages/myVipCard/myVipCard',
        })
    },
    async getNewTeamNum() {
        const result = await getNewTeamList({
            companyId: user.companyId
        })
        this.setData({
            newTeamNum: result.pendingReview
        })
        console.log(result, 'resultresult')
    },
    onFloor() {
        console.log('回调点击出现函数')
        this.setData({
            isLogon: false
        })
    },
    onLogonCancel() {
        console.log('点击取消的回调')
        this.setData({
            isLogon: true
        })
    }
})